package com.gitee.huanminabc.fastboot.orm.aop;

import com.gitee.huanminabc.jcommon.base.SnowIdUtil;
import com.gitee.huanminabc.fastboot.annotation.Aop;
import com.gitee.huanminabc.fastboot.orm.annotation.Transactional;
import com.gitee.huanminabc.fastboot.orm.Propagation;
import com.gitee.huanminabc.fastboot.proxy.InterceptorHandle;
import com.gitee.huanminabc.jlambda_sql.jdbc.TransactionManage;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/5 21:06
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Aop(Transactional.class)
public class TransactionalAop implements InterceptorHandle {

    @Override
    public Object around(Object target, Class<?> realClass, Method method, Object[] args, Callable<?> callable, Map<String,Object> context) throws Exception {
        Transactional annotation = realClass.getAnnotation(Transactional.class);
        if (annotation != null) {
            Propagation propagation = annotation.propagation();
            //如果当前方法上有Transactional注解,则开启事务,如果指定了Propagation.REQUIRES_NEW,则开启新事务不和当前事务关联
            if (propagation == Propagation.REQUIRES_NEW) {
                TransactionManage.openTransaction(SnowIdUtil.uniqueLongHex());
            } else {
                TransactionManage.openTransaction();
            }

            try {
                Object call = callable.call();
                TransactionManage.commitTransaction();
                return call;
            } catch (Exception e) {
                TransactionManage.rollbackTransaction();
                throw e;
            }
        }
        return callable.call();
    }
}
